package com.itheima.web.servlet;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //设置请求编码
            req.setCharacterEncoding("UTF-8");
            //获取要执行的方法名称
            String methodName = req.getParameter("method");
            //获取类的Class字节码对象
            Class clazz = this.getClass();
            //获取method方法对象
            Method method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //方法调用
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      /*  //调用service
        UserService service = new UserServiceImpl();
        List<User> users = service.findAll();
        //将集合存入请求域中
        req.setAttribute("users", users);
        //请求转发到list.jsp
        req.getRequestDispatcher("/list.jsp").forward(req, resp);*/

      //获取分页条件 null a -1
        int pageSize=5;

        try {
            pageSize=Integer.parseInt(req.getParameter("pageSize"));//每页显示条数
            if (pageSize<1){
                pageSize=5;
            }
        } catch (NumberFormatException e) {
           // e.printStackTrace();
        }

        int pageNum=1;

        try {
            pageNum=Integer.parseInt(req.getParameter("pageNum"));//每页显示条数
        } catch (NumberFormatException e) {
          //  e.printStackTrace();
        }

        //调用service查询
        UserService service=new UserServiceImpl();
        PageInfo<User> info=service.findAll(pageNum,pageSize);

        //将数据保存到request域中
        req.setAttribute("pb",info);

        //请求转发到List.jsp
        req.getRequestDispatcher("/list.jsp").forward(req,resp);








    }


    public void login(HttpServletRequest req, HttpServletResponse resp) {
        try {

            //验证码校验
            //获取用户输入的验证码
            String checkCode = req.getParameter("checkCode");
            //获取程序生成，存储在session中的验证码
            HttpSession session = req.getSession();
            String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
            //为了确保验证码是一次性的，获取以后务必要清除验证码
            session.removeAttribute(checkcode_server);
            //判断如果验证码和服务器端不一致，在请求域显示错误信息，并转发到登录页重新登录
            if (!checkCode.equalsIgnoreCase(checkcode_server)) {
                req.setAttribute("msg", "验证码错误");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }


            //验证码用户名和密码
            //设置请求编码
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");
            //获取所有请求参数的集合
            Map<String, String[]> map = req.getParameterMap();
            //将集合封装到User对象
            User u = new User();
            BeanUtils.populate(u, map);
            //让service去查
            UserService service = new UserServiceImpl();
            User existUser = service.login(u);
            //判断登录用户信是否存在
            if (existUser == null) {
                //不存在，使用请求域保存错误信息
                req.setAttribute("msg", "!  用户名或密码错误，请重新登录");
                //转发到登录页，并显示错误信息
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            } else {
                //存在则登录成功将登录信息保存到session域并重定向到首页
                req.getSession().setAttribute("user", existUser);
                resp.sendRedirect(req.getContextPath() + "/index.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public void add(HttpServletRequest req, HttpServletResponse resp) {
        try {
            //获取所有请求参数的集合
            Map<String, String[]> map = req.getParameterMap();
            //将集合封装到User对象
            User u = new User();
            BeanUtils.populate(u, map);
            //将service去添加
            UserService service = new UserServiceImpl();
            service.add(u);
            //重定向到学生列表
            resp.sendRedirect(req.getContextPath() + "/userServlet?method=findAll");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取需要删除的id
        String delid = req.getParameter("delid");
        //让service去删
        UserService service = new UserServiceImpl();
        service.delete(delid);
        //重定向回到列表页
        resp.sendRedirect(req.getContextPath() + "/userServlet?method=findAll");
    }


    public void findById(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取需要修改的id
        String upid = req.getParameter("upid");
        //调用service去查
        UserService service = new UserServiceImpl();
        User user = service.findById(upid);
        //将需要修改的用户信息保存到请求域中
        req.setAttribute("u", user);
        //转发到修改页面，回显进行修改的用户信息
        req.getRequestDispatcher("/update.jsp").forward(req, resp);

    }


    public void update(HttpServletRequest req, HttpServletResponse resp) {
        try {
            //设置请求编码
            req.setCharacterEncoding("UTF-8");
            //获取使用请求参数的集合
            Map<String, String[]> map = req.getParameterMap();
            //把集合封装到User对象
            User user = new User();
            BeanUtils.populate(user, map);
            //让service去修改
            UserService service = new UserServiceImpl();
            service.update(user);
            //重定向到列表页
            resp.sendRedirect(req.getContextPath() + "/userServlet?method=findAll");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

}
